Path Sum
Question
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
|
|
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Analysis
- 不断地在sum上减去当前节点的值看是否为0,递归向下进行。假如某节点为叶节点且sum-root.val==0,返回true
- 也可构建helper函数进行DFS遍历,利用global变量不断加上节点值,判断是否相等
Code
|
|
Path Sum II
Question
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
|
|
return
|
|
Analysis
- DFS遍历过程中碰到加和sum=target将对应序列加入结果res
- 结束一次遍历时需注意 item.remove(item.size()-1); 移走最后一个元素
Code
|
|
Path Sum III
Question
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
|
|
Analysis
- 当遍历到某节点时,找到所以以该节点为终点且取值和可为sum的路径
- 利用presum保存到该节点的所有可能取值和
- 查找res-target是否存在于presum是为了判断是否有可从中间开始计数且满足条件的路径
- 一次遍历结束后需 presum.put(res,presum.get(res)-1); 保证当前存储的都会在后续遍历中构成路径,不影响后续的递归
Code
|
|